function Look(){
    var that = this;
    this._DOMAIN = document.location.host;
    this._WEB_SOCKET_URL = window.location.href.replace(/(http:\/\/)/ig, "ws://").replace(/(\/webchat).+/ig, "") + "/webchat/comet/";
	this._WEBSOCKET_JS_URL = "js/websocket.js";
	this._SCROLL_FLAG = true;
	this._MESSAGE_SIZE = 500;
	this._TIMER = null;
	this._WS = null;
}
var look = new Look();

$(function(){
	look.publicInit.init();
//	$("#sendSubset").text("111"+ JSON.stringify(window.KeyBoard.getString()))
//	setInterval(function() {
//		var js = window.KeyBoard.getString();
//		$("#messageTextarea").val($("#messageTextarea").val() + js);
//	}, 1000);
});

Look.prototype._APP = {//app信息
	Get : function(){
		return $.cookie("app");
	},
	Set : function(app){
		$.cookie("app", app);
	}
}

Look.prototype.User = {
	token : null,//验证令牌
	username : null,
	uid : null
}

Look.prototype.Message = {
	user : look.User,
	content : null
}

Look.prototype._IM10001 = {//发送消息
    getJson: function(content){
		look.Message.content = content;
		return JSON.stringify(look.Message);
    }
}

Look.prototype.publicInit = {
	init: function(){
		$("body").addClass("style_" + look.getHashParam("appid"));
		if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)){
			$("body").addClass("ios");
		}
		
		look.publicInit.reLayout();
    	$(window).resize(look.publicInit.reLayout);
		
		look._APP.Set(look.getHashParam("appid") + look.getHashParam("server_id"));
		look.User.token = look.getHashParam("verify");
		look.User.uid = look.getHashParam("uid");
		look.User.username = escape((look.getHashParam("username")));
		
		if(look._APP.Get() == "" || look.User.uid == ""){
			look.showInfo.error("非法操作…");return false;
		}
		if(typeof(WebSocket) == "undefined"){
			$.getScript(look._WEBSOCKET_JS_URL, function(){
			    look.initLoader.sendLoader();
			});
		}else{ 
			look.initLoader.sendLoader();
		}
	},
    reLayout: function(){
		if(navigator.userAgent.indexOf("Firefox") > 0){
        	$("#messageUl").css("height", parseInt($("body").height()) - parseInt($("#operateCell").height()) - parseInt($(".message_duty").height()));
		}
    },
    autoScroll: function(addHeight, flag){
		var theHeight = document.getElementById("messageUl").scrollHeight - parseInt($("#messageUl").height());
		if (!flag) {return false;}
		$("#messageUl").scrollTop(theHeight);
    }
}

Look.prototype.initLoader = {
    sendLoader: function(){
        look._WS = new WebSocket(look._WEB_SOCKET_URL + look._APP.Get());
        look._WS.onopen = function(event){
            $("#sendSubset").removeClass("a_as_disabled");
			$('#messageUl').html("");
            look.showInfo.show("欢迎加入聊天…");
        }
		look._WS.onmessage = function(event){
            var message = $('#messageUl'), onClass = "";
            var back = JSON.parse(event.data);
            if (back.code == 0) {
                if (back.data.length != 0) {
                    $.each(back.data, function(i, list){
                        list.user.uid == look.User.uid ? onClass = ' class="on"' : onClass = '';
                        message.append(
							'<li' + onClass + '>' +
							'	<p class="message_info"><span class="name">' + list.user.username + '</span><span class="time">' + list.time + '</span></p>' +
                        	'	<p class="message_content">' + list.content.replace(/(\|n)/g, "</br>").replace(/(\|t)/g, "&nbsp;").replace(/(\|')/g, "\"") + '</p>' +
                        	'</li>');
                    });
					if(back.data.length == 1){
						look.publicInit.autoScroll(message.children().last().height(), look._SCROLL_FLAG);
						var messageLength = message.children().length;
						if(messageLength > look._MESSAGE_SIZE){message.children().eq(messageLength - look._MESSAGE_SIZE).prevAll().remove();}
					}else{//第一次加载获取所有聊天记录时，设置滚动条
						look.publicInit.autoScroll(message.innerHeight(), true);
					}
                }
            } else {
				if(back.code == 503){
					$("#operateCell").hide();
				}
                look.showInfo.error(back.code + ":" + back.message);
            }
        }
        look._WS.onclose = function(event){
			look._WS = null;
            look.showInfo.error('连接断开…<a href="javascript:" class="reconnection_subset">重新连接</a>');
			$(".reconnection_subset").bind("click", function(){look.initLoader.sendLoader();});
            $("#sendSubset").addClass("a_as_disabled");
        }
        look._WS.onerror = function(evt){
			look._WS = null;
            look.showInfo.error('连接失败…<a href="javascript:" class="reconnection_subset">重新连接</a>');
			$(".reconnection_subset").bind("click", function(){look.initLoader.sendLoader();});
			$("#sendSubset").addClass("a_as_disabled");
        };
        //[事件]发送
        $("#sendSubset").unbind("click").bind("click", function(){
            if ($(this).hasClass("a_as_disabled")) {return false;}
            var content = $.trim($("#messageTextarea").val()),
				lineSum = content.match(/\n/gi);
            if (look.User.uid == "") {look.showInfo.error("无效用户！", true);return false;}
            if (content == "") {look.showInfo.error("内容不能为空！", true);return false;}
            if (lineSum && lineSum.length > 20) {console.log(lineSum.length);look.showInfo.error("请不要刷屏！", true);return false;}
			if (look.getByteLen(content) > 500) {look.showInfo.error("内容不能超过500字符！", true);return false;}
			if (look.requestCount.init("_IM1001")) {
				look._WS.send(look._IM10001.getJson(look.encodeHtml(content.replace(/"+/g, "|'"))));
            	$("#messageTextarea").val("");
			}
			return false;
        });
		//[事件]滚动
		$("#messageUl").bind("scroll", function(){
			document.getElementById("messageUl").scrollHeight - parseInt($("#messageUl").height()) - $("#messageUl").scrollTop() < 10 ? look._SCROLL_FLAG = true : look._SCROLL_FLAG = false;
		})
		//[事件]焦点
		if (typeof(look._WS.setIsOpenKeyboard) == "function") {
			$("#messageTextarea").bind("focus", function(){
				look._WS.setIsOpenKeyboard(true);
			}).bind("blur", function(){
				look._WS.setIsOpenKeyboard(false);
			});
		}
    }
}

/**
 * 提示信息
 */
Look.prototype.showInfo = {
    add: function(){
        $("#webChatTipsPanel").parents("li").remove();
        $("#messageUl").append('<li><p class="web_chat_tips_panel look_hidden" id="webChatTipsPanel"><span></span></p></li>');
    },
    show: function(text, clear){
        this.add();
        $("#webChatTipsPanel").fadeIn().children("span").removeClass().html(text);
        look.publicInit.autoScroll($("#messageUl").innerHeight(), true);
		if(clear){
			clearTimeout(look._TIMER);
			this.clear();
		}
    },
    right: function(text, clear){
        this.show(text, clear);
        $("#webChatTipsPanel span").addClass("right");
    },
    error: function(text, clear){
        this.show(text, clear);
        $("#webChatTipsPanel span").addClass("error");
    }, 
	clear: function(){
		look._TIMER = setTimeout(function(){
			$("#webChatTipsPanel").parents("li").remove();
		}, 3000);
	}
}

/**
 * 生成id
 * @return
 */
Look.prototype.generateGuid = function(){
    var guid = "";
    for (var i = 1; i <= 8; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
    }
    return guid;
}

/**
 * 返回字符串的字节长度
 * @param val
 * @return int
 */
Look.prototype.getByteLen = function(val){
    var len = 0, str = val.replace(" ", "$"), charCode = -1;
    for (var i = 0; i < str.length; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) {
            len += 1;
        } else {
            len += 2;
        }
    }
    return len;
}

/**
 * 转换html标签
 * @param html
 * @return
 */
Look.prototype.encodeHtml = function(html){
    return html.replace(/</g, "&lt").replace(/>/g, "&gt");
}

/**
 * 获取指定的URL中的hash参数值
 * @param {String} paramName URL参数
 * @return paramValue URL参数值
 */
Look.prototype.getHashParam = function(paramName){
    var paramValue = "";
    var isFound = false;
    if (location.hash.indexOf("#") == 0 && location.hash.indexOf("=") > 1) {
        var arrSource = unescape(location.hash).substring(1, location.hash.length).split("&");
        i = 0;
        while (i < arrSource.length && !isFound) {
            if (arrSource[i].indexOf("=") > 0) {
                if (arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase()) {
                    paramValue = arrSource[i].split("=")[1];
                    isFound = true;
                }
            }
            i++;
        }
    }
    return paramValue;
}

/**
 * 请求计数，放在cookie中
 * @time 保存时间
 * @count 次数后阻止
 */
Look.prototype.requestCount = {
    time: 10,
    count: 3,
    nick: function(){
        if (look.User.username) {
            return look.User.username;
        } else {
            return "";
        }
    },
    init: function(key){
        var $time = this.time, $count = this.count;
        if (!$.cookie(key)) {
            $.cookie(key, 0, {
                expires: $time / 24 / 60 / 60
            });
        }
        if ($.cookie(key) > $count) {
			look.showInfo.error(decodeURI(this.nick()) + "您的发言太频繁了，请休息一会儿…", true);
            return false;
        } else {
            $.cookie(key, parseInt($.cookie(key)) + 1, {
                expires: $time / 24 / 60 / 60
            });
            return true;
        }
    }
}